<template>
  <div style="padding: 20px; width: 100%">
    <h2>用户批量添加</h2>
    <el-form :inline="true" :model="form" :rules="rules" ref="form" label-width="100px" style="padding-left: 200px;">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入联系方式"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="form.address" placeholder="请输入地址"></el-input>
      </el-form-item>
      <el-form-item label="出生日期" prop="birthday">
        <el-date-picker
            v-model="form.birthday"
            type="date"
            :clearable=false
            placeholder="选择日期"
            style="width: 190px"
            :picker-options="pickOptions">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="form.sex">
          <el-radio label="男">男</el-radio>
          <el-radio label="女">女</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <div style="margin-left: 35vw;">
      <el-button type="primary" @click="add" size="medium">添加到列表</el-button>
      <el-button type="danger" @click="reset" size="medium">重置</el-button>
      <el-button type="primary" @click="commit" size="medium" style="margin-left: 30vw">提交表格</el-button>
    </div>

    <el-table :data="tableData" stripe style="margin-top: 20px;flex: 1">
      <el-table-column type="index" label="序号" style="margin-right: 5px"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="password" label="密码"></el-table-column>
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="phone" label="电话"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="200px"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
      <el-table-column prop="age" label="年龄"></el-table-column>
      <el-table-column prop="sex" label="性别"></el-table-column>
      <el-table-column label="操作" width="150px">
        <template v-slot="scope">
          <el-button type="primary" @click="$router.push('' + scope.row.id)">编辑</el-button>
          <el-popconfirm
              title="确定删除吗？"
              @confirm="del(scope.row.id)"
          >
            <el-button type="danger" slot="reference" style="margin-left: 5px">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "AddUser",
  data() {
    const checkUsername = (rule, value, callback) => {
      if(!value){
        callback(new Error('请输入用户名'));
      }else if (!/^[a-zA-Z0-9]{3,30}$/.test(value)) {
        callback(new Error('用户名长度3-30位，由数字或英文字母组成'));
      }
      callback();
    };
    const checkPassword = (rule, value, callback) => {
      if(!value){
        callback(new Error('请输入密码'));
      }else if (!/^\w{5,30}$/.test(value)) {
        callback(new Error('密码长度5-30位，由数字、26个英文字母或者下划线组成'));
      }
      callback();
    };
    const checkPhone = (rule, value, callback) => {
      if(!value){
        callback(new Error('请输入号码'));
      }else if (!/^[1][3-9][0-9]{9}$/.test(value)) {
        callback(new Error('请输入正确的号码'));
      }
      callback();
    };
    const checkEmail = (rule, value, callback) => {
      if(!value){
        callback();
      }else if (!/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
        callback(new Error('请输入正确的邮箱'));
      }
      callback();
    };
    return {
      form: {
        sex: '男',
        birthday: new Date()
      },
      tableData:[],
      rules: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'},
        ],
        username: [
          {validator: checkUsername, required: true, trigger: 'blur'}
        ],
        password: [
          {validator: checkPassword, required: true, trigger: 'blur'}
        ],
        phone: [
          {validator: checkPhone, required: true, trigger: 'blur'}
        ],
        email:[
          {validator: checkEmail, trigger: 'blur'}
        ]
      },
      pickOptions: {
        disabledDate(time){
          return time.getTime() > Date.now();
        }
      }
    }
  },
  methods: {
      add(){
        this.$refs["form"].validate((valid) => {
          async function checkUsername(vm, username) {
            try {
              const index = vm.tableData.findIndex(item => item.username === username);
              if (index === -1) {
                const res = await request.get('/user/checkUsername/' + username);
                return res.code === "200"
              } else {
                return false;
              }
            } catch (e) {
              return true;
            }
          }
          if(valid){
            checkUsername(this, this.form.username).then(res => {
              if(res) {
                this.tableData.push(JSON.parse(JSON.stringify(this.form)));
                this.$notify.success({title: "", message: '成功添加到列表', position: 'bottom-left'});
                this.$refs["form"].resetFields();
              }
              else{
                this.$notify.error({title: "", message: '用户名已存在', position: 'bottom-left'});
              }
            })
          }
        })
      },
    reset() {
      this.$refs["form"].resetFields()
    },
    del(id){
      const index = this.tableData.findIndex(item => item.id === id);
      if(index !== -1){
        this.tableData.splice(index, 1);
      }
    },
    commit() {
      request.post('/user/addlist', this.tableData).then(res => {
        if (res.code === "200") {
          this.$notify.success({title: "", message: '批量添加成功', position: 'bottom-left'});
          this.$refs["form"].resetFields();
          this.tableData = []
        } else {
          this.$notify.error({title: "", message: res.msg, position: 'bottom-left'});
        }
      })
    },
  }
}
</script>